from django.shortcuts import render
from ihome_project.utils.view import LoginRequiredMixin
from django.views import View
import json
from django import http
from apps.houses.models import House
from .models import Order
import datetime
from django.conf import settings


# Create your views here.

# 添加订单页面和拉取订单列表
class Add_orders(LoginRequiredMixin, View):
    def post(self, request):
        """添加订单"""

        # 获取登录用户id ( 继承了扩展类自动验证是否登录)
        user = request.user
        # 提取参数
        messages_dict = json.loads(request.body.decode())
        house_id = messages_dict['house_id']
        start_date = messages_dict['start_date']
        end_date = messages_dict['end_date']

        # 验证参数
        if not all([house_id, start_date, end_date]):
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })

        # 查找用户选择的房屋
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })
        house_price = house.price
        result = datetime.datetime.strptime(end_date, '%Y-%m-%d') - datetime.datetime.strptime(start_date,
                                                                                               '%Y-%m-%d')  # 日期相加减问题
        days = result.days
        amount = house_price * days

        # 创建订单
        try:
            order = Order.objects.create(
                user=user,
                house=house,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house_price,
                amount=amount,
                status=Order.ORDER_STATUS["WAIT_ACCEPT"]

            )
        except Exception as e:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })

        # 响应
        return http.JsonResponse({
            "data": {
                "order_id": order.id
            },
            "errno": "0",
            "errmsg": "下单成功"

        })

    def get(self, request):
        """拉取订单列表"""

        user = request.user

        role = request.GET.get('role')

        # 验证
        if not role:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })

        if role not in ['custom', 'landlord']:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })

        # 根据用户id 提取 订单信息 houses 信息
        if role == 'custom':
            # 查询当前自己下了哪些单
            orders = Order.objects.filter(user=user).order_by('-create_time')
            # house_ids = [order.house_id for order in orders]
            # houses = House.objects.filter(id__in=house_ids)

        else:
            # 查询自己房屋有哪些订单

            houses = House.objects.filter(user=user)
            house_ids = [house.id for house in houses]
            orders = Order.objects.filter(house_id__in=house_ids).order_by("-create_time")

        # 构造数据
        orders_list = []
        try:
            for order in orders:
                # for house in houses:
                house = House.objects.get(id=order.house_id)
                orders_list.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": settings.QNY_HOST + str(house.index_image_url),
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": order.ORDER_STATUS_ENUM[order.status],
                    "title": house.title
                })

        except Exception as e:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })
        # 响应
        return http.JsonResponse({
            'data': {
                'orders': orders_list
            },
            'errmsg': 'ok',
            'errno': 0

        })


# 接单 拒单视图
class AcceptOrder(LoginRequiredMixin, View):
    def put(self, request, order_id):

        # 提取参数
        message_dict = json.loads(request.body.decode())
        action = message_dict.get('action')

        if not action:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })
        if action not in ['accept', 'reject']:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })
        order = Order.objects.get(id=order_id, status=Order.ORDER_STATUS["WAIT_ACCEPT"])

        # 判断是否接受数据
        try:
            if action == 'accept':
                order.status = Order.ORDER_STATUS['WAIT_COMMENT']

            # 拒绝
            else:
                reason = message_dict.get('reason')
                if not reason:
                    return http.JsonResponse({
                        "errno": "4004",
                        "errmsg": "数据错误"})

                order.status = Order.ORDER_STATUS['REJECTED']
                order.comment = reason

            # 保存更改状态
            order.save()
        except Exception as e:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })

        return http.JsonResponse({
            "errno": "0",
            "errmsg": "操作成功"

        })


class Comment(LoginRequiredMixin, View):
    """订单评价"""

    def put(self, request, order_id):

        message_dict = json.loads(request.body.decode())

        comment = message_dict.get('comment')

        if not comment:
            return http.JsonResponse({
                "errno": "4004",
                "errmsg": "数据错误"
            })
        try:
            order = Order.objects.get(id=order_id, status=Order.ORDER_STATUS['WAIT_COMMENT'])
            house = order.house
            # 更新数据
            house.order_count += 1
            order.status = Order.ORDER_STATUS["COMPLETE"]
            order.comment = comment

            house.save()
            order.save()
        except Exception as e:
            return http.JsonResponse({
                'errno': 4004,
                'errmsg': '评论失败'
            })

        return http.JsonResponse({
            "errno": "0",
            "errmsg": "评论成功"

        })
